<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style >
  td{
    text-align: center;
  }
</style>
<body>
  <div id="app">
      <h1>选择你要买的书籍</h1>
      <ul>
        <li v-for="item in books" :key="item.id">
           <span>{{item.name}}</span><button @click="toBuy(item.id)">购买</button>
        </li>
      </ul>
      <hr>
      <table border style="width:500px;margin:20px auto;">
        <thead>
          <tr>
            <th>序号</th>
            <th>书名</th>
            <th>单价</th>
            <th>数量</th>
            <th>合计</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in books" :key="item.id">
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
            <td>{{item.price}}</td>
            <td>{{item.num}}</td>
            <td>{{item.num*item.price}}</td>
          </tr>
        </tbody>
      </table>
      <div>
        <h1>总价格为：{{totalPrice}}</h1>
      </div>
     
  </div>
  <script src="./vue.js"></script>
  <script>

      new Vue({
         el:"#app",
         data(){
            return{
               books:[
                  {id:1,name:"水浒传",price:87,num:0},
                   {id:2,name:"西游记",price:192,num:0},
                   {id:3,name:"三国演义",price:219,num:0},
                  {id:4,name:"红楼梦",price:178,num:0}
               ]
            }
         },
         methods:{
          toBuy(id){
          // 循环所有数据
            this.books.forEach(item=>{
              if(item.id===id){ // 根据当前行id找到对应数据 
                 item.num++;//  //将数据的num  +1
              }
            })
          }
         },
         computed:{
          totalPrice(){ //计算总价的计算属性
            let sum=0;
            this.books.forEach(item=>{
               sum+=item.num*item.price
            })
            return sum
          }
         }
      })



  </script>
</body>
</html>